package com.ktgj.flight.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ktgj.common.core.domain.R;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.BusinessOrder;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.service.IFlightOrderChangeService;
import com.ktgj.flight.vo.FlightOrderInfoVo;
import com.ktgj.pay.api.domain.UnionPayQRCodeResponseApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.flight.service.IFlightOrderInfoService;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 机票预订_机票订单基本信息Controller
 * 
 * @author ruoyi
 * @date 2021-10-26
 */
@ControllerAdvice
@RestController
@RequestMapping("/infos")
public class FlightOrderInfoController extends BaseController {
    @Autowired
    private IFlightOrderInfoService flightOrderInfoService;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private   IFlightOrderChangeService orderChangeService;
    /**
     * 查询机票预订_机票订单基本信息列表
     */
    @PreAuthorize(hasPermi = "flight:info:list")
    @GetMapping("/list")
    public TableDataInfo list(FlightOrderInfo flightOrderInfo) {
        startPage();
        List<FlightOrderInfo> list = flightOrderInfoService.selectFlightOrderInfoList(flightOrderInfo);
        return getDataTable(list);
    }

    /**
     * 导出机票预订_机票订单基本信息列表
     */
    @PreAuthorize(hasPermi = "flight:info:export")
    @Log(title = "机票预订_机票订单基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FlightOrderInfo flightOrderInfo) throws IOException {
        List<FlightOrderInfo> list = flightOrderInfoService.selectFlightOrderInfoList(flightOrderInfo);
        ExcelUtil<FlightOrderInfo> util = new ExcelUtil<FlightOrderInfo>(FlightOrderInfo.class);
        util.exportExcel(response, list, "机票预订_机票订单基本信息数据");
    }

    /**
     * 获取机票预订_机票订单基本信息详细信息
     */
    @PostMapping(value = "/getInfo")
    public AjaxResult getInfo(@RequestBody Map<String, Long> map) {
        Long orderId = map.get("orderId");
        return AjaxResult.success(flightOrderInfoService.selectFlightOrderInfoById(orderId));
    }

    /**
     * 新增机票预订_机票订单基本信息
     */
//    @PreAuthorize(hasPermi = "flight:info:add")
//    @Log(title = "机票预订_机票订单基本信息", businessType = BusinessType.INSERT)
    @PostMapping("/addFlightOrder")
    public AjaxResult addFlightOrder(@RequestBody FlightOrderInfo flightOrderInfo)
    {
        int rows = flightOrderInfoService.insertFlightOrderInfo(flightOrderInfo);
        if (rows > 0)
        {
            return AjaxResult.success("新建机票订单成功！");
        }
        return AjaxResult.error("新建机票订单失败！");
    }
    /**
     * 待处理订单退票的
     */
    @PostMapping("/FlightOrderPending")
    public TableDataInfo getFlightOrderPending(@RequestBody FlightOrderPending flightOrderPending) {
        startPage();
        List<FlightOrderPending> list =orderChangeService.selectFlightOrderPending(flightOrderPending);
        return getDataTable(list);
    }

    /**
     * 修改机票预订_机票订单基本信息
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody FlightOrderInfo flightOrderInfo) {
        return toAjax(flightOrderInfoService.updateFlightOrderInfo(flightOrderInfo));
    }

    /**
     * 修改出票途径
     */
    @PostMapping("/updateTicketChannel")
    public AjaxResult updateTicketChannel(@RequestBody Map<String, String> map) {
        FlightOrderInfo flightOrderInfo = new FlightOrderInfo();
        String orderId = map.get("orderId");
        String ticketChannel = map.get("ticketChannel");
        flightOrderInfo.setOrderId(Long.valueOf(orderId));
        flightOrderInfo.setTicketChannel(ticketChannel);
        return toAjax(flightOrderInfoService.updateFlightOrderInfo(flightOrderInfo));
    }

    /**
     * 删除机票预订_机票订单基本信息
     */
    @PreAuthorize(hasPermi = "flight:info:remove")
    @Log(title = "机票预订_机票订单基本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds) {
        return toAjax(flightOrderInfoService.deleteFlightOrderInfoByIds(orderIds));
    }

    /**
     * 我的-订单列表（机票）
     */
    @PostMapping("/selectAirTicketsOrderList")
    public AjaxResult selectAirTicketsOrderList(HttpServletRequest request) {
        String token = request.getHeader("token");
        Long customerId = remoteCustomerService.getLoginCustomerByToken(token).getData().getCustomerId();
        if (customerId != null && customerId != 0){
            List<AirTicketsVo> airTicketsVoList = flightOrderInfoService.selectAirTicketsVo(customerId);
            if (airTicketsVoList != null && airTicketsVoList.size() > 0){
                return AjaxResult.success(airTicketsVoList);
            }
            else {
                return AjaxResult.error("未查到数据");
            }
        }
        else {
            return AjaxResult.error("登录已过期");
        }
    }

    /**
     * 我的-订单列表（机票-详细信息）
     */
    @PostMapping("/selectAirTicketsDetails")
    public AjaxResult selectAirTicketsDetails(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        Long orderId = Long.valueOf(map.get("orderId").toString());
        R<Customer> customerR = remoteCustomerService.getLoginCustomerByToken(token);
        Long customerId = customerR.getData().getCustomerId();
        return AjaxResult.success(flightOrderInfoService.selectFlightOrderInfoByOrderId(orderId, customerId));
    }

    /**
     * 我的-订单列表（机票-基本信息）删除订单
     */
    @PostMapping("/deleteAirTicketsInformation")
    public AjaxResult deleteAirTicketsInformation(@RequestBody Map<String, Object> map) {
        String ordernum = map.get("ordernum").toString();

        BusinessOrder businessOrder = remoteCustomerService.selectBusinessOrderByOrdernum(ordernum);

        Long customerId = businessOrder.getCustomerId();

        return toAjax(flightOrderInfoService.updateFlightOrderInfoByOrdernum(customerId));
    }

    /**
     * 我的-订单列表（机票-基本信息）取消订单
     */
    @PostMapping("/cancelAirTicketsBasic")
    public AjaxResult cancelAirTicketsBasic(@RequestBody Map<String, Object> map) {
        String ordernum = map.get("ordernum").toString();
        FlightOrderInfoVo flightOrderInfoVo = new FlightOrderInfoVo();
        flightOrderInfoVo.setOrdernum(ordernum);

        BusinessOrder businessOrder = remoteCustomerService.selectBusinessOrderByOrdernum(ordernum);

        Long customerId = businessOrder.getCustomerId();
        flightOrderInfoVo.setCustomerId(customerId);

        return toAjax(flightOrderInfoService.updateFlightOrderInfoByOrdernumPnrstatus(flightOrderInfoVo));
    }

    /**
     * 我的-订单列表（机票-基本信息）修改订单
     */
    @PostMapping("/updateAirTicketsBasic")
    public AjaxResult updateAirTicketsBasic(@RequestBody Map<String, Object> map) {
        String guestIdno = map.get("guestIdno").toString();
        String contactPhone = map.get("contactPhone").toString();
        String contactName = map.get("contactName").toString();
        String ordernum = map.get("ordernum").toString();
        FlightOrderInfoVo flightOrderInfoVo = new FlightOrderInfoVo();
        flightOrderInfoVo.setGuestIdno(guestIdno);
        flightOrderInfoVo.setContactName(contactName);
        flightOrderInfoVo.setContactPhone(contactPhone);
        flightOrderInfoVo.setOrdernum(ordernum);
        return toAjax(flightOrderInfoService.updateFlightOrderInfoByFlightOrderInfoVo(flightOrderInfoVo));
    }

    /**
     * 我的-订单列表（机票-基本信息）立即支付（状态修改）
     */
    @PostMapping("/toPayAirTicketsBasic")
    public AjaxResult toPayAirTicketsBasic(@RequestBody Map<String, Object> map) {
        String ordernum = map.get("ordernum").toString();
        FlightOrderInfoVo flightOrderInfoVo = new FlightOrderInfoVo();
        flightOrderInfoVo.setOrdernum(ordernum);

        BusinessOrder businessOrder = remoteCustomerService.selectBusinessOrderByOrdernum(ordernum);

        Long customerId = businessOrder.getCustomerId();
        flightOrderInfoVo.setCustomerId(customerId);

        return toAjax(flightOrderInfoService.updateFlightOrderInfoByOrdernumPnrstatus(flightOrderInfoVo));
    }

    /**
     * 查询订单列表（机票）远
     * */
    @PostMapping("/checkTheTicketList")
    public List<TicketOrder> checkTheTicketList(@RequestBody Map<String, Object> map){
        Long customerId = Long.valueOf(map.get("customerId").toString());
        String type = map.get("typa").toString();
        List<TicketOrder> ticketOrderList = flightOrderInfoService.checkTheTicketList(customerId, type);
        return ticketOrderList;
    }

    /**
     * 订单详情
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/orderDetails")
    public AjaxResult queryFlightOrderInfoByOrderId(HttpServletRequest request, @RequestBody Map<String, Object> map) throws Exception {
        String token = request.getHeader("token");
        Long orderId = Long.valueOf(map.get("orderId").toString());
        OrderDetails details = null;
        if (token != null) {
            try {
                details = flightOrderInfoService.queryFlightOrderInfoByOrderId(token, orderId);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
        } else {
            details = flightOrderInfoService.queryFlightOrderInfoByOrderId(null, orderId);
        }
        return AjaxResult.success(details);
    }

    /**
     * 订单列表
     * @param request
     * @return
     */
    @PostMapping("/flightOrderInfoList")
    public AjaxResult flightOrderInfoList(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        R<Customer> customer;
        try {
            customer = remoteCustomerService.getLoginCustomerByToken(token);
            Long customerId = customer.getData().getCustomerId();
            String status = map.get("status").toString();
            List<FlightOrderList> orderList = flightOrderInfoService.flightOrderInfoList(customerId, status);
            return AjaxResult.success(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.expired("登录已过期，请重新登录");
        }
    }

    /**
     * 订单列表(CRM)
     * @param map
     * @return
     */
    @PostMapping("/flightOrderInfoListCRM")
    public TableDataInfo flightOrderInfoListCRM(@RequestBody Map<String, Object> map) {
        startPage();
        try {
            Long customerId = Long.valueOf(map.get("customerId").toString());
            String status = map.get("status").toString();
            List<FlightOrderList> orderList = flightOrderInfoService.flightOrderInfoList(customerId, status);
            return getDataTable(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 填写订单
     * @param request
     * @param orderEnter
     * @return
     */
    @PostMapping("/fillOrder")
    public AjaxResult fillOrder(HttpServletRequest request, @RequestBody FlightFillOrderEnter orderEnter) {
        try {
            FlightFillOrder fillOrder = flightOrderInfoService.fillOrder(request, orderEnter);
            return AjaxResult.success(fillOrder);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.expired(e.getMessage());
        }
    }

    /**
     * 订单收银台
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/selectFlightOrderInfo")
    public AjaxResult selectFlightOrderInfo(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        Long orderId = Long.valueOf(map.get("orderId").toString());
        String businessType = String.valueOf(map.get("businessType"));
        FlightOrderCashier orderInfo = flightOrderInfoService.selectFlightOrderInfo(token, orderId, businessType);
        return AjaxResult.success(orderInfo);
    }

    /**
     * 微信小程序支付
     * @param map
     * @return
     */
    @PostMapping("/wechatPay")
    public AjaxResult wechatPay(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String openId = map.get("openId");
        String orderNumber = map.get("orderNumber");

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount"));
        }

        String type = map.get("type");

        Map<String, Object> wechat;
        try {
            wechat = flightOrderInfoService.wechatPay(openId, orderNumber, amount, type, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (wechat != null)
            return AjaxResult.success(wechat);
        else
            return AjaxResult.error("支付失败");
    }

    /**
     * 改签微信小程序支付
     * @param map
     * @return
     */
    @PostMapping("/wechatPayChange")
    public AjaxResult wechatPayChange(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String openId = map.get("openId");
        String orderNumber = map.get("orderNumber");
        BigDecimal payAmount = new BigDecimal(map.get("payAmount"));

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount"));
        }

        String type = map.get("type");

        Map<String, Object> change;
        try {
            change = flightOrderInfoService.wechatPayChange(openId, orderNumber, payAmount, amount, type, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (change != null)
            return AjaxResult.success(change);
        else
            return AjaxResult.error("支付失败");
    }

    /**
     * 银联二维码支付码获取
     * @param map
     * @return
     */
    @PostMapping("/getQRCode")
    public AjaxResult getQRCode(HttpServletRequest request, @RequestBody Map<String, String> map) {
        UnionPayQRCodeResponseApi qrCode;
        try {
            qrCode = flightOrderInfoService.getQRCode(map, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (qrCode != null)
            return AjaxResult.success(qrCode);
        else
            return AjaxResult.error("银联二维码支付码获取失败！");
    }

    /**
     * 改签订单银联二维码支付码获取
     * @param map
     * @return
     */
    @PostMapping("/getQRCodeChange")
    public AjaxResult getQRCodeChange(HttpServletRequest request, @RequestBody Map<String, String> map) {
        UnionPayQRCodeResponseApi qrCodeChange;
        try {
            qrCodeChange = flightOrderInfoService.getQRCodeChange(map, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (qrCodeChange != null)
            return AjaxResult.success(qrCodeChange);
        else
            return AjaxResult.error("银联二维码支付码获取失败！");
    }

    /**
     * 机票分析（未使用）
     * @param request
     * @param flightAnalysis
     * @return
     */
    @PostMapping("/flightAnalysis")
    public AjaxResult flightAnalysis(HttpServletRequest request, @RequestBody FlightAnalysisVO flightAnalysis) {
        String token = request.getHeader("token");
        R<Customer> customerR;
        try {
            customerR = remoteCustomerService.getLoginCustomerByToken(token);
            FlightAnalysisDTO flightAnalysisDTO = flightOrderInfoService.flightAnalysis(customerR.getData().getCustomerId(), flightAnalysis.getStartDate(), flightAnalysis.getEndDate());
            return AjaxResult.success(flightAnalysisDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 机票分析
     * @param request
     * @param analysisFlight
     * @return
     */
    @PostMapping("/analysisFlight")
    public AjaxResult analysisFlight(HttpServletRequest request, @RequestBody AnalysisFlightVO analysisFlight) {
        String token = request.getHeader("token");
        R<Customer> customerR;
        try {
            customerR = remoteCustomerService.getLoginCustomerByToken(token);
            List<AnalysisFlightDTO> flightDTOS = flightOrderInfoService.analysisFlight(customerR.getData().getCustomerId(), analysisFlight);
            return AjaxResult.success(flightDTOS);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 机票订单详情（CRM）
     * @param map
     * @return
     */
    @PostMapping("/orderFlightDetails")
    public AjaxResult orderFlightDetails(@RequestBody Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        OrderFlightDetails flightDetails;
        try {
            flightDetails = flightOrderInfoService.orderFlightDetails(orderId);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        if (flightDetails != null) {
            return AjaxResult.success(flightDetails);
        } else {
            return AjaxResult.error("系统错误");
        }
    }

    /**
     * 机票退票详情（CRM）
     * */
    @PostMapping("/refundOrderFlight")
    public AjaxResult refundOrderFlight(@RequestBody Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        OrderFlightDetails flightDetails;
        try {
            flightDetails = flightOrderInfoService.refundOrderFlight(orderId);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (flightDetails != null) {
            return AjaxResult.success(flightDetails);
        } else {
            return AjaxResult.error("系统错误");
        }
    }

    /**
     * 改签核对-核对订单信息
     * @param map
     * @return
     */
    @PostMapping("/changeFlightOrder")
    public AjaxResult changeFlightOrder(@RequestBody Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        String ticketNo = String.valueOf(map.get("ticketNo"));
        ChangeFlightOrder flightOrder = flightOrderInfoService.changeFlightOrder(orderId, ticketNo);
        if (flightOrder != null)
            return AjaxResult.success(flightOrder);
        else
            return AjaxResult.error("查询失败");
    }

    /**
     * 机票订单列表（CRM）
     * @param order
     * @return
     */
    @PostMapping("/flightOrderList")
    public TableDataInfo flightOrderList(@RequestBody FlightOrderDTOCRM order) {
        startPage();
        List<FlightOrderListVO> orderList = flightOrderInfoService.flightOrderList(order);
        return getDataTable(orderList);
    }

    /**
     * 机票订单列表（CRM）
     * @param order
     * @return
     */
    @PostMapping("/orderList")
    public List<FlightOrderListVO> orderList(@RequestBody FlightOrderDTOCRM order) {
        List<FlightOrderListVO> orderList = flightOrderInfoService.flightOrderList(order);
        return orderList;
    }

    @PostMapping("/queryFlightOrderNumber")
    public int queryFlightOrderNumber(@RequestBody Long customerId) {
        return flightOrderInfoService.queryFlightOrderNumber(customerId);
    }

    /**
     * 行程机票订单
     * */
    @PostMapping("/journeyFlightOrderInfo")
    public JourneyFlightOrderInfoVo journeyFlightOrderInfo(@RequestBody Map<String, Object> map) {
        Long orderId = Long.valueOf(map.get("orderId").toString());
        JourneyFlightOrderInfoVo journeyFlightOrderInfoVo = flightOrderInfoService.journeyFlightOrderInfo(orderId);
        return journeyFlightOrderInfoVo;
    }

    /**
     * 机票订单(远成)---id
     * */
    @PostMapping("/selFlightOrderInfoById")
    public List<FlightOrderInfoTickets> selFlightOrderInfoById(@RequestBody Map<String, Object> map) {
        Long orderId = Long.valueOf(map.get("orderId").toString());
        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoService.selFlightOrderInfoById(orderId);
        return flightOrderInfoTickets;
    }

    /**
     * 机票订单(远成)---无id
     * */
    @PostMapping("/selFlightOrderInfo")
    public List<FlightOrderInfoTickets> selFlightOrderInfo(@RequestBody FlightOrderInfoTickets flightOrderInfoTickets) {
        List<FlightOrderInfoTickets> flightOrderInfoTicketList = flightOrderInfoService.selFlightOrderInfo(flightOrderInfoTickets);
        return flightOrderInfoTicketList;
    }

    /**
     * 获取支付订单列表
     * */
    @PostMapping("/payList")
    public List<FlightOrderInfo> payList(@RequestBody Map<String, Object> map) {
        String airline = map.get("airline").toString();
        String start = map.get("start").toString();
        String end = map.get("end").toString();
        List<FlightOrderInfo> flightOrderInfoTickets = flightOrderInfoService.payList(airline, start, end);
        return flightOrderInfoTickets;
    }

    /**
     * 回填备注
     * */
    @PostMapping("/backfillRemarks")
    public int backfillRemarks(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        String remark = map.get("remark").toString();
        int i = flightOrderInfoService.backfillRemarks(id, remark);
        return i;
    }

    /**
     * 订单号获取机票订单信息（远程）
     * */
    @PostMapping("/order")
    public FlightOrderInfo order(@RequestBody Map<String, Object> map){
        Long orderId = Long.valueOf(map.get("orderId").toString());
        FlightOrderInfo flightOrderInfo = flightOrderInfoService.order(orderId);
        return flightOrderInfo;
    }

    /**
     * 获取机票订单待跟进订单
     */
    @PostMapping("/flightOrderListThings")
    public List<FlightOrderList> orderListThings()
    {
        return flightOrderInfoService.orderListThings();
    }
}